<?php
/**
 * Created by PhpStorm.
 * User: 76683
 * Date: 2018/7/15
 * Time: 22:16
 */

namespace app\api\controller;

use app\api\until\WeChat;
use app\api\model\WeUsers;
use app\api\until\Token;

class Login extends Base
{
    /**
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function signIn()
    {
        if ($this->request->isGet()) {
            list($this->code, $this->msg) = [0, '请求方法错误'];
            return;
        }
        if ($this->request->isPost()) {
            //获取小程序code
            $data = $this->request->post();
            $res = $this->validate($data, 'app\api\validate\Login.login');
            if (true !== $res) {
                list($this->code, $this->msg) = [0, $res];
                return;
            }
            //请求验证
            $weChat = new WeChat();
            //验证
            $is_weChat = $weChat->start()->getSessionKey($data['code'])->verify($data['raw_data'], $data['signature']);
            if (true === $is_weChat) {
                //通过验证 存下微信用户信息 并下发token
                $data = $weChat->getUserInfo($data['raw_data']);
                $userModel = new WeUsers();
                $user_info = $userModel->saveUser($data);
                if (empty($user_info)) {
                    list($this->code, $this->msg) = [0, '注册失败'];
                    return;
                } else {
                    $tokenModel = new Token();
                    $token = $tokenModel->makeToken($user_info['id']);
                    $user_info['token'] = $token;
                    $user_info['nick_name'] = isset($user_info['we_nick_name']) ? $user_info['we_nick_name'] : (isset($user_info['reset_name']) ? $user_info['reset_name'] : $user_info['nick_name']);
                    list($this->code, $this->msg, $this->data) = [1, '登录成功', $user_info];
                    return;
                }
            } else {
                list($this->code, $this->msg) = [0, '微信验证异常请重新登录'];
                return;
            }
        }
    }
}